package com.chookss.tiku

import android.text.TextUtils
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.chookss.tiku.entity.AnswerRecord
import com.chookss.tiku.response.AnswerRecordList
import com.chookss.tools.httpForm
import com.johnrambo.ktea.base.BaseViewModel

/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2021/01/06
 * Note: 我的答题记录
 */
class ExamRecordViewModel() : BaseViewModel() {

    var recordType: String? = null//	false	String	数据类型 智能推荐1专项2模拟3正式考试4
    var periodName: String? = null//	false	String	期间，格式yyyyMM

    //下载记录列表

    private val allAnswerRecords = ArrayList<AnswerRecord>()

    fun downloadAnswerRecords(pageNo: Int, pageSize: Int): LiveData<PageResult> {
        var liveResult = MutableLiveData<PageResult>()

        val params2: MutableMap<String, Any?> = HashMap()
        if (!TextUtils.isEmpty(recordType)) {
            params2["recordType"] = recordType
        }
        if (!TextUtils.isEmpty(periodName)) {
            params2["periodName"] = periodName
        }
        params2["pageNum"] = (pageNo + 1).toString()
        params2["pageSize"] = pageSize.toString()

        jobs + httpForm<AnswerRecordList.Response> {
            url = "api/sys/my/getMyAnswerRecord"
            params = params2
            onSuccess = {
                addToAnswerRecordList(pageNo, pageSize, it.data?: emptyList())
                liveResult.postValue(PageResult(pageNo, pageSize, it.data?: emptyList(), allAnswerRecords, true))
            }
            onError = {
                liveResult.postValue(PageResult(pageNo, pageSize, emptyList(), emptyList(), false, it))
            }
        }
        return liveResult
    }

    //判断最后一页是否有重复的, 做下去重
    private fun existInAnswerRecordList(msg: AnswerRecord, pageSize: Int): Boolean {
        var start = Math.max(0, allAnswerRecords.size - pageSize)
        var end = allAnswerRecords.size
        if (end > start) {
            for (i in start until end) {
//                我们这个是联合的主键，resp_serial_no+org_code+ngw_account 组成唯一
                if (allAnswerRecords[i].pmKey == msg.pmKey) {
                    return true
                }
            }
        }
        return false
    }

    private fun addToAnswerRecordList(pageNo: Int, pageSize: Int, loadData: List<AnswerRecord>) {
        if (pageNo == 0) {
            allAnswerRecords.clear()
        }
        loadData.forEach {
            if (!existInAnswerRecordList(it, pageSize)) {
                allAnswerRecords.add(it)
            }
        }
    }

    data class PageResult(
            val pageNo: Int,
            val pageSize: Int,
            val loadData: List<AnswerRecord>,
            val allData: List<AnswerRecord>,
            val success: Boolean,
            val error: String? = null)

}
